package com._54programer.ws;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import com.hazelcast.core.HazelcastInstance;

import lombok.extern.slf4j.Slf4j;

/**
 * @author SN
 * @date Created by on 2019/11/29
 * @description ApplicationContext 被初始化或刷新时，该事件被触发
 */
@Component
@Slf4j
public class WsBoot implements ApplicationListener<ContextRefreshedEvent> {

	@Value("${ws.port}")
	int port;

	@Value("${ws.opencluster}")
	boolean cluster;

	@Autowired
	private SID SSID;
	
	@Autowired
	private HazelcastInstance Hi;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		if (event.getApplicationContext().getParent() == null) {
			try {
				
				WsServer.getInstance().start(port, cluster);
				
				if (cluster) {
					Map<String, Object> ss = new HashMap<String, Object>();
					ss.put("sname", SSID.ID());
					Hi.getSet(Const.SERVER_INFO).add(ss);
					log.info("集群服务开启成功!当前服务器标识：{}", SSID.ID());
				}
				
			} catch (Exception e) {
				log.error("Ws服务端启动失败: " + e.getMessage());
			}
		}
	}
}